package com.admin.web;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.admin.model.FileMeta;
import com.admin.model.ProjectWithPassCount;
import com.admin.service.AdminCTSService;
import com.admin.service.AdminProjectService;
import com.admin.service.AdminSchoolService;
import com.admin.util.AdminProjectExcelTool;
import com.common.model.AdminUser;
import com.common.model.ClassInfo;
import com.common.model.College;
import com.common.model.Department;
import com.common.model.Project;
import com.common.model.StudentUser;
import com.common.model.TeacherUser;

@Controller
@RequestMapping("/admin/project")
public class AdminProjectWeb {
	@Autowired
	AdminSchoolService schooService;
	@Autowired
	AdminCTSService ctsService;
	@Autowired
	AdminProjectService prjService;
	/**
	 * 根据条件查询题目
	 * @param clgId 学院id
	 * @param page 页码(从1开始)
	 * @return
	 */
	@RequestMapping("/showProject/{clg_id}/{page}")
	public ModelAndView showProject(
			@PathVariable("clg_id") int clgId,
			@PathVariable("page")int page){
		ModelAndView mav=new ModelAndView();
		mav.setViewName("admin/project/showProject");
		mav.addObject("colleges", schooService.getAllCollege());
		int minClgId=schooService.getMinCollegeId();
		if(clgId<minClgId){
			clgId=minClgId;
		}
		mav.addObject("departments", schooService.getDepsOfCollege(clgId));
		int projectCount=prjService.getAllProjcetsCountByCollege(clgId);
		int totalPage=(int)Math.ceil(projectCount/10.0);
		if(totalPage==0){
			totalPage=1;
		}
		if(page>totalPage){
			page=totalPage;
		}
		mav.addObject("clgId", clgId);
		mav.addObject("page", page);
		mav.addObject("project",prjService.getAllProjcetsByCollege(clgId, page));
		mav.addObject("projectCount",projectCount );
		mav.addObject("totalPage",totalPage);
		mav.addObject("currentMenu", "showProjectList");
		return mav;
	}
	/**
	 * 删除一个题目
	 * @param prjId
	 * @return -1无权限
	 */
	@ResponseBody
	@RequestMapping("/deleteProject/{prj_id}")
	public int deleteProject(@PathVariable("prj_id")int prjId,HttpSession session){
		AdminUser admin=(AdminUser)session.getAttribute("user");
		Project prj=prjService.getProjectByPrjId(prjId);
		if(prj==null){
			return 0;
		}
		int prjClgId=prj.getTeacher().getDepartment().getCollege().getId();
		if(!(admin.isSuperAdmin()||admin.getCollegeId()==prjClgId)){
			return -1;
		}
		prjService.deleteProject(prjId);
		return 0;
	}
	/**
	 * 显示修改题目信息界面
	 * @param prjId
	 * @return
	 */
	@RequestMapping("/showUpdateProject/{prj_id}")
	public ModelAndView showUpdateProject(@PathVariable("prj_id")int prjId,HttpSession session){
		ModelAndView mav=new ModelAndView();
		Project prj=prjService.getProjectByPrjId(prjId);
		AdminUser admin=(AdminUser)session.getAttribute("user");
		int prjClgId=prj.getTeacher().getDepartment().getCollege().getId();
		if(!(admin.isSuperAdmin()||admin.getCollegeId()==prjClgId)){
			mav.setViewName("common/error");
			mav.addObject("error", "该题目并不是您学院的,请勿非法操作");
			return mav;
		}
		int prjDepId=prj.getTeacher().getDepartment().getId();
		mav.setViewName("admin/project/updateProject");
		mav.addObject("colleges", schooService.getAllCollege());
		mav.addObject("departments", schooService.getDepsOfCollege(prjClgId));
		mav.addObject("prjClgId", prjClgId);
		mav.addObject("prjDepId", prjDepId);
		mav.addObject("project",prj);
		mav.addObject("currentMenu", "showProjectList");
		return mav;
	}
	/**
	 * 修改一个题目
	 * @param prj
	 * @return -1 参数错误; -2无专业方向信息 -3审阅和指导老师不在同一个系 -4无权限
	 */
	@ResponseBody
	@RequestMapping("/updateProject")
	public int updateProject(Project prj,@RequestParam("branches[]")ArrayList<String>branches, HttpSession session){
		if(prj.getId()==null||prj.getName()==null||prj.getName().trim().isEmpty()||prj.getTea_id()==null||prj.getShengyue_tea_id()==null){
			return -1;
		}
		if(branches==null||branches.size()==0){
			return -2;
		}
		//适合于添加到数据库的数据
		ArrayList<Integer> branchIdArr= new ArrayList<>();
		try {
			for (String branch : branches) {
				Integer branchId=Integer.parseInt(branch);
				if(!branchIdArr.contains(branchId)){//不重复添加数据
					branchIdArr.add(branchId);
				}
			}
		} catch (Exception e) {
			return -1;
		}
		if(branchIdArr.size()==0){
			return -2;
		}
		Department prjTDep=ctsService.getTeacherByTeacherId(prj.getTea_id()).getDepartment();
		Department prjSDep=ctsService.getTeacherByTeacherId(prj.getShengyue_tea_id()).getDepartment();
		if(prjTDep.getId()!=prjSDep.getId()){
			return -3;
		}
		AdminUser admin=(AdminUser)session.getAttribute("user");
		int prjTClgId=ctsService.getTeacherByTeacherId(prj.getTea_id()).getDepartment().getCollege().getId();
		if(!(admin.isSuperAdmin()||admin.getCollegeId()==prjTClgId)){
			return -4;
		}
		for (Integer branch : branchIdArr) {
			int branchClgId=schooService.getProBranchByPbId(branch).getProf().getDepartment().getCollege().getId();
			if(!(admin.isSuperAdmin()||admin.getCollegeId()==branchClgId)){
				return -4;
			}
		}
		prjService.updateProject(prj,branchIdArr);
		return 0;
	}
	/**
	 * 删除题目附件,任务书,论文
	 * @param type 1 附件,2任务书,3论文
	 * @param prjId 题目id
	 * @return -1 无权限
	 */
	@ResponseBody
	@RequestMapping("/deleteProjectFile/{prjId}/{type}")
	public int deleteProjectFile(@PathVariable("type")int type,@PathVariable("prjId")int prjId,HttpSession session){
		Project prj=prjService.getProjectByPrjId(prjId);
		AdminUser admin=(AdminUser)session.getAttribute("user");
		int prjClgId=prj.getTeacher().getDepartment().getCollege().getId();
		if(!(admin.isSuperAdmin()||admin.getCollegeId()==prjClgId)){
			return -1;
		}
		prjService.deleteProjectFile(type, prjId);
		return 0;
	}
	/**
	 * 修改题目附件,论文等
	 * @param file
	 * @param session
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping("/uploadProjectFile/{prjId}/{type}")
	public ArrayList<FileMeta> uploadProjectFile(MultipartFile file,@PathVariable("prjId")int prjId,@PathVariable("type")int type,HttpSession session) throws IOException{
		Project prj=prjService.getProjectByPrjId(prjId);
		AdminUser admin=(AdminUser)session.getAttribute("user");
		int prjClgId=prj.getTeacher().getDepartment().getCollege().getId();
		if(!(admin.isSuperAdmin()||admin.getCollegeId()==prjClgId)){
			return new ArrayList<>();
		}
		FileMeta fileMeta=new FileMeta();
		fileMeta.setFileName(file.getOriginalFilename().toLowerCase());
		fileMeta.setFileSize(file.getSize()/1024.0+"kb");
		fileMeta.setFileType(file.getContentType());
		prjService.updateProjectFile(file, prjId, type);
		ArrayList<FileMeta> arr=new ArrayList<FileMeta>();
		arr.add(fileMeta);
		return arr;
	}
	/**
	 * 显示修改题目
	 * @return
	 */
	@RequestMapping("/showInsertProject")
	public ModelAndView showInsertProject(){
		ModelAndView mav=new ModelAndView();
		mav.setViewName("admin/project/insertProject");
		mav.addObject("colleges", schooService.getAllCollege());
		mav.addObject("currentMenu", "showProjectList");
		return mav;
	}
	/**
	 * 增加一个题目
	 * @param prj
	 * @return -1 参数错误; -2无专业方向信息 -3审阅和指导老师不在同一个系 -4无权限
	 */
	@ResponseBody
	@RequestMapping("/insertProject")
	public int insertProject(Project prj,@RequestParam("branches[]")ArrayList<String>branches, HttpSession session){
		if(prj.getName()==null||prj.getName().trim().isEmpty()||prj.getTea_id()==null||prj.getShengyue_tea_id()==null){
			return -1;
		}
		if(branches==null||branches.size()==0){
			return -2;
		}
		//适合于添加到数据库的数据
		ArrayList<Integer> branchIdArr= new ArrayList<>();
		try {
			for (String branch : branches) {
				Integer branchId=Integer.parseInt(branch);
				if(!branchIdArr.contains(branchId)){//不重复添加数据
					branchIdArr.add(branchId);
				}
			}
		} catch (Exception e) {
			return -1;
		}
		if(branchIdArr.size()==0){
			return -2;
		}
		Department prjTDep=ctsService.getTeacherByTeacherId(prj.getTea_id()).getDepartment();
		Department prjSDep=ctsService.getTeacherByTeacherId(prj.getShengyue_tea_id()).getDepartment();
		if(prjTDep.getId()!=prjSDep.getId()){
			return -3;
		}
		AdminUser admin=(AdminUser)session.getAttribute("user");
		int prjTClgId=ctsService.getTeacherByTeacherId(prj.getTea_id()).getDepartment().getCollege().getId();
		if(!(admin.isSuperAdmin()||admin.getCollegeId()==prjTClgId)){
			return -4;
		}
		for (Integer branch : branchIdArr) {
			int branchClgId=schooService.getProBranchByPbId(branch).getProf().getDepartment().getCollege().getId();
			if(!(admin.isSuperAdmin()||admin.getCollegeId()==branchClgId)){
				return -4;
			}
		}
		prjService.insertProject(prj,branchIdArr);
		return 0;
	}
	/**
	 * 由excel导入题目
	 * @param excel
	 * @param session
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping("/insertProjectByExcel")
	public ArrayList<FileMeta> insertProjectByExcel(MultipartFile excel,HttpSession session) throws IOException{
		FileMeta file=new FileMeta();
		file.setFileName(excel.getOriginalFilename().toLowerCase());
		file.setFileSize(excel.getSize()/1024.0+"kb");
		file.setFileType(excel.getContentType());
		file.setInputStresm(excel.getInputStream());
		prjService.insertProjectByExcel(file, session);
		ArrayList<FileMeta> arr=new ArrayList<FileMeta>();
		arr.add(file);
		return arr;
	}
	@RequestMapping("/showInsertReport")
	public ModelAndView showInsertByExcelResult( HttpSession session){
		ModelAndView mav=new ModelAndView();
		if(session.getAttribute("projectExcelReadResult")==null){
			mav.setViewName("redirect:showProject/1/1");
			return mav;
		}
		mav.setViewName("admin/project/importProjectReport");
		mav.addObject("report", session.getAttribute("projectExcelReadResult"));
		mav.addObject("successCount", session.getAttribute("projectExcelReadSuccessCount"));
		session.removeAttribute("projectExcelReadResult");
		session.removeAttribute("projectExcelReadSuccessCount");
		mav.addObject("currentMenu", "showProjectList");
		return mav;
	}
	@RequestMapping("/projectList.xlsx")
	public void getPrjList2007(HttpServletResponse response){
		try {
			AdminProjectExcelTool.exportTo2007(prjService.getAllProject()).write(response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}	
	@RequestMapping("/projectList.xls")
	public void getPrjList2003(HttpServletResponse response){
		try {
			AdminProjectExcelTool.exportTo2003(prjService.getAllProject()).write(response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 根据条件查询题目
	 * @param clgId 学院id
	 * @param page 页码(从1开始)
	 * @return
	 */
	@RequestMapping("/showProjectAuth/{page}")
	public ModelAndView showProjectAuth(
			@PathVariable("page")int page,
			HttpSession session){
		ModelAndView mav=new ModelAndView();
		mav.setViewName("admin/project/showProjectAuth");
		int projectCount=0;
		ArrayList<ProjectWithPassCount> prjCList=null;
		AdminUser admin=(AdminUser)session.getAttribute("user");
		if(admin.isSuperAdmin()){
			projectCount=prjService.getUnAutoProjectCountByAll();
		}else{
			projectCount=prjService.getUnAutoProjectCountByCollege(admin.getCollegeId());
		}
		
		int totalPage=(int)Math.ceil(projectCount/10.0);
		if(totalPage==0){
			totalPage=1;
		}
		if(page>totalPage){
			page=totalPage;
		}
		if(admin.isSuperAdmin()){
			prjCList=prjService.getUnAutoProjectByAll(page);
		}else{
			prjCList=prjService.getUnAutoProjectByCollege(admin.getCollegeId(),page);
		}
		mav.addObject("page", page);
		mav.addObject("projectC",prjCList);
		mav.addObject("projectCount",projectCount );
		mav.addObject("totalPage",totalPage);
		mav.addObject("currentMenu", "showProjectAuth");
		return mav;
	}	
	/**
	 * 审核不通过
	 * @param prjId
	 * @param failReason
	 * @param session
	 * @return -1 无权限
	 */
	@ResponseBody
	@RequestMapping("/failProject/{prj_id}")
	public int failProject(@PathVariable("prj_id")int prjId,String failReason,HttpSession session){
		AdminUser admin=(AdminUser)session.getAttribute("user");
		int prjClgId=prjService.getProjectByPrjId(prjId) .getTeacher().getDepartment().getCollege().getId();
		if(!(admin.isSuperAdmin()||admin.getCollegeId()==prjClgId)){
			return -1;
		}
		if(failReason==null||failReason.trim().isEmpty()){
			return -2;
		}
		prjService.failProject(prjId, failReason.trim());
		return 0;
	}
	/**\
	 * 批量通过审核
	 * @param prjidList
	 * @param session
	 * @return -1
	 */
	@ResponseBody
	@RequestMapping("/passProject")
	public int passProject(@RequestParam("prjIdList[]")ArrayList<Integer> prjIdList,HttpSession session){
		AdminUser admin=(AdminUser)session.getAttribute("user");
		if(!admin.isSuperAdmin()){
			for (Integer prjId : prjIdList) {
				int prjClgId=prjService.getProjectByPrjId(prjId) .getTeacher().getDepartment().getCollege().getId();
				if(admin.getCollegeId()!=prjClgId){
					return -1;
				}
			}
		}
		prjService.passProject(prjIdList);
		return 0;
	}
	@ResponseBody
	@RequestMapping("/getProjectByPrjId/{prj_id}")
	public Project getProjectByPrjId(@PathVariable("prj_id")int prjId){
		return prjService.getProjectByPrjId(prjId);
	}
}
